﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SQLite;

namespace festivalDatabase
{
    public partial class startScreen : userInterface
    {
        public startScreen()
        {
            InitializeComponent();
            setFonts();
            musicPanel.Visible = false;
            setupPics();
            dbAccess = new dbAccessor();
            setupUserTable();
            // debug - enters the username and password for us!
            userTextBox.Text = "buddy guy";
            passwordTextBox.Text = "theblues";
        }

        private void setFonts()
        {
            this.loginLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.userTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.passwordTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.passwordTextBox.ForeColor = System.Drawing.Color.White; //cheap hack to make text appear invisible - easily defeated by highlighting text
            this.loginButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.musicButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.artButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chooseFestivalTypeLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 13F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.changePassButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        }

        private void setupPics()
        {
            setIcon();
            startScreenLogo.Image = new Bitmap("startScreenLogo.tif");
            startScreenLogo.SizeMode = PictureBoxSizeMode.Zoom;
            musicPictureBox.Image = new Bitmap("musicFestivalLogo.tif");
            musicPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            artPictureBox.Image = new Bitmap("artFestivalLogo.tif");
            artPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
            musicFestivalWatermark.Image = new Bitmap("musicFestivalWatermark.tif");
            musicFestivalWatermark.SizeMode = PictureBoxSizeMode.Zoom;
            artFestivalWatermark.Image = new Bitmap("artFestivalWatermark.tif");
            artFestivalWatermark.SizeMode = PictureBoxSizeMode.Zoom;
        }

        protected void clearDatabase(object sender, System.EventArgs e)
        {
            dbAccess.dropAllTables();
        }

        private void loginButton_Click(object sender, EventArgs e)
        {
            loginErrorProvider.Clear();

            if (userTextBox.Text == "")
            {
                loginErrorProvider.SetError(userTextBox, "Username cannot be blank");
            }
            else if (passwordTextBox.Text == "")
            {
                loginErrorProvider.SetError(passwordTextBox, "Password cannot be blank");
            }
            else if (checkLogin(userTextBox.Text, passwordTextBox.Text))
            {
                loginSuccessful();
            }
            else
            {
                loginErrorProvider.SetError(loginButton, "Username or password incorrect!");
            }

            passwordTextBox.Clear();
        }

        public bool checkLogin(string username, string password)
        {
            bool loginCorrect = false;

            SQLiteCommand query = dbAccess.getCommand();
            query.CommandText = "SELECT * " +
                                "FROM db_user;";
            DataTable dt = dbAccess.executeQuery(query);

            foreach (DataRow row in dt.Rows)
            {
                if (row["username"].ToString() == username)
                {
                    if (row["password"].ToString() == password)
                        loginCorrect = true;
                }
            }

            return loginCorrect;
        }

        private void setupUserTable()
        {
            // first, check to see if the db_user wasn't cleared, in which case we'll load the previous password
            SQLiteCommand query = dbAccess.getCommand();
            query.CommandText = "SELECT username " + 
                                "FROM db_user " +
                                "WHERE username == 'festivalPlanner';";
            DataTable dt = dbAccess.executeQuery(query);

            foreach (DataRow row in dt.Rows)
            {
                if (row["username"].ToString() == "festivalPlanner")
                    return;
            }

            // if we haven't return'd by now, the database was cleared and we need to insert the default user
            SQLiteCommand nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "INSERT INTO db_user " +
                                   "VALUES ('festivalPlanner', 'password')";
            dbAccess.executeNonQuery(nonQuery);
        }

        private void loginSuccessful()
        {
            loginPanel.Visible = false;
            festivalTypeSelectPanel.Visible = true;
            logoutButton.Visible = true;
            SQLiteCommand query = dbAccess.getCommand();
            query.CommandText = "SELECT * " +
                                "FROM db_user " +
                                "WHERE username = @User;";

            query.Parameters.Add("@User", DbType.String);
            query.Parameters["@User"].Value = userTextBox.Text.ToString();
            currentUser = dbAccess.executeQuery(query);
            populateDatabaseButton.Visible = false;
        }

        private void clearDBCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (clearDBCheckBox.Checked == true)
            {
                this.FormClosing += new FormClosingEventHandler(clearDatabase);
            }
            else
            {
                this.FormClosing -= clearDatabase;
            }
        }

        /// <summary>
        /// Invoked when user clicks the button for music festival planning.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void musicButton_Click(object sender, EventArgs e)
        {
            festivalTypeSelectPanel.Visible = false;
            musicPanel.Visible = true;
            clearDBCheckBox.Visible = true;
            updateFestivalList("Music");
            goBackButton.Visible = true;
        }

        public void updateFestivalList(string festival_type)
        {
            musicFestivalSelectComboBox.Items.Clear();
            artFestivalSelectComboBox.Items.Clear();

            SQLiteCommand query = dbAccess.getCommand();

            query.CommandText = "SELECT * " +
                                "FROM festival " +
                                "WHERE festival_type = @Type;";
            SQLiteParameter param = new SQLiteParameter("@Type", festival_type);
            query.Parameters.Add(param);

            try
            {
                festivals = dbAccess.executeQuery(query);

                foreach (DataRow row in festivals.Rows)
                {
                    if (festival_type == "Music")
                        musicFestivalSelectComboBox.Items.Add((string)(row["name"].ToString() + ", " + row["id"].ToString()));
                    else
                        artFestivalSelectComboBox.Items.Add((string)(row["name"].ToString() + ", " + row["id"].ToString()));
                }
            }
            catch
            {
                musicFestivalSelectComboBox.Items.Add("Error loading festivals");
            }
        }

        private void artButton_Click(object sender, EventArgs e)
        {
            festivalTypeSelectPanel.Visible = false;
            artPanel.Visible = true;
            clearDBCheckBox.Visible = true;
            updateFestivalList("Art");
            goBackButton.Visible = true;
            
        }

        private void changePassButton_Click(object sender, EventArgs e)
        {
            changePassword changePass = new changePassword(dbAccess, currentUser);
            changePass.Show();
        }

        private void musiciansButton_Click(object sender, EventArgs e)
        {
            editMusician musicianEditor = new editMusician(dbAccess, currentFestivalType, currentFestivalID);
            musicianEditor.Show();
        }

        private void scheduleButton_Click(object sender, EventArgs e)
        {
            editMusicianSchedule scheduleEditor = new editMusicianSchedule(dbAccess, currentFestivalID);
            scheduleEditor.Show();
        }

        private void musicVendorButton_Click(object sender, EventArgs e)
        {
            string stringPassIn = "Festival name: " + musicFestivalSelectComboBox.Text;
            editVendors vendorEditor = new editVendors(dbAccess, festivalTypes.Music, stringPassIn);
            vendorEditor.Show();
        }

        private void musicSponsorButton_Click(object sender, EventArgs e)
        {
            editSponsors sponsorEditor = new editSponsors(dbAccess, festivalTypes.Music);
            sponsorEditor.Show();
        }

        private void stageButton_Click(object sender, EventArgs e)
        {
            editStages stageEditor = new editStages(dbAccess, musicFestivalSelectComboBox.Text);
            stageEditor.Show();
        }

        private void musicReportButton_Click(object sender, EventArgs e)
        {
            viewReports reportRunner = new viewReports(dbAccess, currentFestivalID);
            reportRunner.Show();
        }

        private void musicFestivalSelectComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            enableMusicButtons();
            currentFestivalID = Int32.Parse(festivals.Rows[musicFestivalSelectComboBox.SelectedIndex]["id"].ToString());
        }

        private void enableMusicButtons()
        {
            deleteMusicFestivalButton.Enabled = true;
            editMusicFestivalButton.Enabled = true;
            musiciansButton.Enabled = true;
            scheduleMusicianButton.Enabled = true;
            musicVendorButton.Enabled = true;
            musicSponsorButton.Enabled = true;
            musicReportButton.Enabled = true;
            stageButton.Enabled = true;
        }

        private void disableMusicButtons()
        {
            deleteMusicFestivalButton.Enabled = false;
            editMusicFestivalButton.Enabled = false;
            musiciansButton.Enabled = false;
            scheduleMusicianButton.Enabled = false;
            musicVendorButton.Enabled = false;
            musicSponsorButton.Enabled = false;
            musicReportButton.Enabled = false;
            stageButton.Enabled = false;
        }

        private void deleteFestivalButton_Click(object sender, EventArgs e)
        {
            SQLiteCommand nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE " +
                                   "FROM festival " +
                                   "WHERE id = @Id;";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;

            dbAccess.executeNonQuery(nonQuery);
            musicFestivalSelectComboBox.Text = "";
            disableMusicButtons();
            musicFestivalSelectComboBox.Text = "";
            updateFestivalList("Music");
            System.Windows.Forms.MessageBox.Show("Festival deleted.");

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM music_festival_has_stage " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM festival_has_fine_artist " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM festival_has_sponsor " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM musician_plays " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM festival_has_vendor " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);
        }

        private void addMusicFestivalButton_Click(object sender, EventArgs e)
        {
            newFestival festivalAdder = new newFestival(dbAccess);
            festivalAdder.Show();
            festivalAdder.FormClosing += new FormClosingEventHandler(updateFestivalListFormClosed);
        }

        private void editMusicFestivalButton_Click(object sender, EventArgs e)
        {
            editMusicFestival festivalEditer = new editMusicFestival(dbAccess, currentFestivalID);
            festivalEditer.Show();
            festivalEditer.FormClosing += new FormClosingEventHandler(updateFestivalListFormClosed);
        }

        private void updateFestivalListFormClosed(object sender, EventArgs e)
        {
            if (musicPanel.Visible)
                updateFestivalList("Music");
            else
                updateFestivalList("Art");
        }

        private void artVendorButton_Click(object sender, EventArgs e)
        {
            string stringPassIn = "Festival name: " + musicFestivalSelectComboBox.Text;
            editVendors vendorEditor = new editVendors(dbAccess, festivalTypes.Art, stringPassIn);
            vendorEditor.Show();
        }

        private void addArtFestivalButton_Click(object sender, EventArgs e)
        {
            newFestival festivalAdder = new newFestival(dbAccess);
            festivalAdder.Show();
            festivalAdder.FormClosing += new FormClosingEventHandler(updateFestivalListFormClosed);
        }

        private void deleteArtFestivalButton_Click(object sender, EventArgs e)
        {
            SQLiteCommand nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE " +
                                   "FROM festival " +
                                   "WHERE id = @Id;";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;

            dbAccess.executeNonQuery(nonQuery);
            artFestivalSelectComboBox.Text = "";
            disableArtButtons();
            updateFestivalList("Art");

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM music_festival_has_stage " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM festival_has_fine_artist " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM festival_has_sponsor " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM musician_plays " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);

            nonQuery = dbAccess.getCommand();
            nonQuery.CommandText = "DELETE FROM festival_has_vendor " +
                                   "WHERE festival_id=@Id";
            nonQuery.Parameters.Add("@Id", DbType.Int16);
            nonQuery.Parameters["@Id"].Value = currentFestivalID;
            dbAccess.executeNonQuery(nonQuery);
        }

        private void disableArtButtons()
        {
            deleteArtFestivalButton.Enabled = false;
            editArtFestivalButton.Enabled = false;
            editFineArtistsButton.Enabled = false;
            artVendorButton.Enabled = false;
            artSponsorButton.Enabled = false;
            artReportButton.Enabled = false;
        }

        private void enableArtButtons()
        {
            deleteArtFestivalButton.Enabled = true;
            editArtFestivalButton.Enabled = true;
            editFineArtistsButton.Enabled = true;
            artVendorButton.Enabled = true;
            artSponsorButton.Enabled = true;
            artReportButton.Enabled = true;
        }

        private void artReportButton_Click(object sender, EventArgs e)
        {
            viewReports reportRunner = new viewReports(dbAccess, currentFestivalID);
            reportRunner.Show();
        }

        private void editFineArtistsButton_Click(object sender, EventArgs e)
        {
            editFineArtist artistEditor = new editFineArtist(dbAccess, artFestivalSelectComboBox.Text, currentFestivalID);
            artistEditor.Show();
        }

        private void artFestivalSelectComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            enableArtButtons();
            currentFestivalID = Int32.Parse(festivals.Rows[artFestivalSelectComboBox.SelectedIndex]["id"].ToString());
        }

        private void editArtFestivalButton_Click(object sender, EventArgs e)
        {
            editMusicFestival festivalEditor = new editMusicFestival(dbAccess, currentFestivalID);
            festivalEditor.Show();
            festivalEditor.FormClosing += new FormClosingEventHandler(updateFestivalListFormClosed);
        }

        private void goBackButton_Click(object sender, EventArgs e)
        {
            festivalTypeSelectPanel.Visible = true;
            musicPanel.Visible = false;
            artPanel.Visible = false;
            goBackButton.Visible = false;
            clearDBCheckBox.Visible = false;
        }

        private void logoutButton_Click(object sender, EventArgs e)
        {
            loginPanel.Visible = true;
            festivalTypeSelectPanel.Visible = false;
            musicPanel.Visible = false;
            artPanel.Visible = false;
            goBackButton.Visible = false;
            logoutButton.Visible = false;
            userTextBox.Text = "";
            passwordTextBox.Text = "";
            clearDBCheckBox.Visible = false;
            populateDatabaseButton.Visible = true;
        }

        private void artSponsorButton_Click(object sender, EventArgs e)
        {
            editSponsors sponsorEditor = new editSponsors(dbAccess, festivalTypes.Art);
            sponsorEditor.Show();
        }

        private void populateDatabase_Click(object sender, EventArgs e)
        {
            dbAccess.dropAllTables();
            dbAccess.createTables();
            dbAccess.populateDatabase();
        }
    }
}
